package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendCodeMessage(@RequestBody User user,
                             HttpSession session){
        //1、后台获取手机号【13399998888】
        String phone = user.getPhone();
        //2、随机生成六位数字验证码【123456】
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        //3、调用SMSUtils,给该手机号发送相应的验证码短信
        // SMSUtils.sendMessage("antman","SMS_136010026",phone,code);
        System.out.println(code);
        //4、将该验证码存入到session中，使用手机号作为key，值就是验证码
        // session.setAttribute(phone,code.toString());
        //
        redisTemplate.opsForValue().set("code:"+phone,code,5, TimeUnit.MINUTES);
        return R.success("发送验证码成功");
    }



    @PostMapping("/login")
    public R login(@RequestBody Map<String,String> map,
                   HttpSession session){
        //2、收到用户输入的手机号【13399998888】+验证码【666666】
        String phone = map.get("phone");
        String code = map.get("code");
        //3、和真实的验证码【在哪呢？从session中取验证码】进行比对
        //String loginCode = (String) session.getAttribute(phone);
        String loginCode = String.valueOf(redisTemplate.opsForValue().get("code:" + phone));

        if(code.equals(loginCode)){
            // 比对成功：验证码正确，登录成功
            // 判断当前用户是否为新用户：如果是新用户，我要将他添加到user表中
            // select * from user where phone = ?
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            qw.eq(User::getPhone,phone);
            User one = userService.getOne(qw);
            if(one == null){//当前用户是新用户，需要添加到User表中
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            //登录成功，将用户信息存入到session中
            session.setAttribute("user",one.getId());

            //删除redis中的验证码
            redisTemplate.delete("code:"+phone);
            return R.success("登录成功！");
        }else {
            // 比对失败：验证码错误，登录失败
            return R.error("验证码错误!");
        }
    }


    @PostMapping("/loginout")
    public R logout(HttpSession httpSession){
        httpSession.invalidate();
        return R.success("退出成功！");
    }
}
